package com.bms.admin.config;

import java.util.Map;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.bms.admin.base.index.model.NowUser;
import com.bms.auth.SubjectUtil;
import com.feilong.core.Validator;

@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(com.bms.admin.config.annotation.LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
    	String token = request.getHeader("token");
    	Map<String,Object> params = SubjectUtil.getInstance().getTokenParams(token);
    	NowUser user = new NowUser();
    	if(Validator.isNotNullOrEmpty(params)){
    		user.setUserId(Long.parseLong(params.get("id").toString()));
    		user.setUsername(params.get("username").toString());
    		user.setCompanyId(Long.parseLong(params.get("companyId").toString()));
    	}
        return user;
    }
}
